package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@Controller
public class UserController {


    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping("/loginPage.do")
    public String loginPage(){

        return "login";
    }


    @RequestMapping("/login2.do")
    public String login2(User user,Model model){
        System.out.println(user);

        model.addAttribute("name",user.getName());

        return "success";
    }


    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, HttpServletRequest request, HttpServletResponse response, Model model){

        //1. 非空验证
        if (result.hasErrors()){
            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());
            return "login";
        }
        //2.  验证 用户名  密码

      User userDB =   userMapper.selectByName(loginUser.getName());

        if (userDB == null){
            model.addAttribute("error","用户名不存在");
            return "login";
        }

        //3. 校验密码
        String loginUserPassword = loginUser.getPassword();

        String salt = userDB.getSalt();
        String password = userDB.getPassword();

        String md5String = Md5Utils.getMD5String(loginUserPassword + salt);

        if (!md5String.equals(password)){
            model.addAttribute("error","密码错误");
            return "login";
        }

        // 4. 加密用户信息  制作token令牌  把token令牌放到cookie里 把cookie返回给浏览器 ，浏览器会自动保存cookie

        TokenUtils.responseTokenByCookie(userDB,response,30);


        // 5. 把用户信息存储到Redis  30分钟过期

        redisTemplate.opsForValue().set(userDB.getName(), JSON.toJSONString(userDB),30, TimeUnit.MINUTES);

        return "redirect:list.do";
    }


}
